import 'dart:convert';

class Item {
  late int id;
  late String name;

  Item(this.id, this.name);

  String toString(){
    return json.encode(toMap());
  }

  Item.fromMap(Map m) {
    id = m['id'];
    name = m['name'];
  }

  Map toMap() {
    return {'id': id, 'name': name};
  }
}

class Data {
  late bool status;
  late String msg;
  late List<Item> data1;
  dynamic data2;
  List<Item>? data3;

  Data(this.status, this.msg, this.data1,{this.data3});

  String toString(){
    return json.encode(toMap());
  }
  Data.fromMap(Map m){
    status = m['status'];
    msg = m['msg'];
    data1 = (m['data1'] as List<dynamic>).map((e) => Item(e['id'], e['name'])).toList();
    data2 = m['data2'];
    data3 = m['data3'];
    // data3 = (m['data3'] as List<dynamic>).map((e) => Item(e['id'], e['name'])).toList();
    // data3 = m['data3']==null?null:(m['data3'] as List<dynamic>).map((e) => Item(e['id'], e['name'])).toList();
    print("${m['data3']}  ${m['data4']}");
  }
  
  Map toMap() {
    var d1 = List<Map>.empty(growable: true);
    data1.forEach((v) {
      d1.add(v.toMap());
    });
    var d2 = data1.map((e) => e.toMap()).toList();
    return {'status': status, 'msg': msg, 'data1': d2, 'data2': data2};
  }
}

typedef ListData = List<Item> ;
typedef JsonMap = Map<String, dynamic>;

main() {
  Data data =
      Data(true, "ok", List.filled(10, Item(1, "zing"), growable: true));
  String res = json.encode(data.toMap());
  print(res);

  var d = json.decode(res);
  print(d);
  print(Data.fromMap(d));
  print(Data.fromMap(d).data1);

  Data data2 =
  Data(true, "ok", List.empty());
  String res2 = json.encode(data2.toMap());
  print(res2);

  var d2 = json.decode(res2);
  print(d2);
  print(Data.fromMap(d2));
  print(Data.fromMap(d2).data1);

  var list = List.filled(10, Item(1, "zing"), growable: true);
  print(list.toString());
  (json.decode(list.toString()) as List<dynamic>).map((e) => Item.fromMap(e));
  print(list);
  // var listData = ListData.from(json.decode(list.toString()));
  // print(listData);
}
